package DataStructure.linkList;

import java.util.ArrayList;

/**
 * 61. 旋转链表 https://leetcode.cn/problems/rotate-list/
 */
public class RotateRight {

    /**
     * 1. 末尾指向head
     * 2. 新末尾指向null
     * 3. 获取新head返回
     */
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null) {
            return head;
        }
        ListNode p = head;
        ArrayList<ListNode> nodeArray = new ArrayList<>();
        while(p != null) {
            nodeArray.add(p);
            p = p.next;
        }
        int len = nodeArray.size();
        nodeArray.get(len-1).next = nodeArray.get(0);
        int newLastIndex = len - k%len -1;
        int newHeadIndex = (newLastIndex+1)%len;
        nodeArray.get(newLastIndex).next = null;
        return nodeArray.get(newHeadIndex);
    }

}
